// import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';
import "regenerator-runtime/runtime.js";
import axios from "axios";;
import './index.css';


let previewFrame = document.getElementById("preview");
let currentFile = null;

// let es = new EventSource('http://localhost:3000/update');

// es.onopen = function () {
//     console.log("Connection to server opened.");
// };
// es.onmessage = function(e) {
//     console.log(`onmessage: ${e}`);
// } 
// es.addEventListener('edit',function(e){
//     previewFrame.contentWindow.location.reload();
// });
// // 连接异常时会触发 error 事件并自动重连
// es.addEventListener('error', e => {
//     if (e.target.readyState === EventSource.CLOSED) {
//         console.log('Disconnected');
//     } else if (e.target.readyState === EventSource.CONNECTING) {
//         console.log('Connecting...');
//     }
// }, false);


const input = document.querySelector('input[type=file]');
const saveBtn = document.querySelector('.save-btn');
let monacoInstance = null;


/** 编辑器构造函数 */
class MonacoEditor {
    constructor(dom, options) {
        this.instance = monaco.editor.create(dom, options);
    }
    setValue(value) {
        this.instance.setValue(value);
    }
    getValue(value) {
        return this.instance.getValue();
    }
}


/** input事件 */
input.addEventListener('change', () => {
    const reader = new FileReader()
    currentFile = input.files[0];
    reader.readAsText(input.files[0], 'utf8') // input.files[0]为第一个文件
    reader.onload = () => {
        if (monacoInstance == null) {
            monacoInstance = new MonacoEditor(document.getElementById("monaco"), {
                value: reader.result,
                curTheme: 'vs-dark',

            });
            monacoInstance.instance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function () {
                alert('保存成功');
            })
            return;
        }
        monacoInstance.setValue(reader.result);
    }
}, false);


saveBtn.addEventListener('click', async () => {
    if (!monacoInstance) {
        return alert('请选择文件');
    }
    if (monacoInstance.getValue().length == 0) {
        return alert('内容不得为空');
    }
    postCode(currentFile, monacoInstance.getValue());
});

function postCode(file, code) {
    axios({
            url: 'http://localhost:3000/saveCode',
            method: 'POST',
            data: {
                code: code,
                filename: currentFile.name,
            },
        })
        .then(res => {
            previewFrame.contentWindow.location.reload();
        })
        .catch(err => {
            console.log(err);
        });
}